// Licensed to Cloudera, Inc. under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  Cloudera, Inc. licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import { useState, useEffect } from 'react';
import huePubSub from '../../huePubSub';

// Basic helper hook to let a component subscribe to a huePubSub topic and rerender for each message
// by placing the message/info in a state that is automatically updated.

// Use with caution and preferably only at the top level component in your component tree since
// we don't want to have states stored all over the app.

// When a callback is provided the state will not be updated.

export function useHuePubSub<T>({
  topic,
  callback,
  app
}: {
  topic: string;
  callback?: (info: T) => void;
  app?: string;
}): T | undefined {
  const [huePubSubState, setHuePubSubState] = useState<{ info: T | undefined }>({
    info: undefined
  });

  useEffect(() => {
    const pubSub = huePubSub.subscribe<T>(
      topic,
      info => {
        if (callback) {
          callback(info);
        } else {
          // Always create a new state so that the React component is re-rendered even
          // if the info is the same as previous info. This is to stay aligned with the idea
          // of having a component being notified for EVERY message for the topics it subscribes to.
          setHuePubSubState(() => ({ info }));
        }
      },
      app
    );

    return () => {
      // Remove huePubSub subscription
      pubSub.remove();
    };
  });

  return huePubSubState.info;
}
